package movie.ticketing.system.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class DatabaseInitializer {
    private final SystemDB systemDB;
    private JFrame startupFrame;

    public DatabaseInitializer() {
        this.systemDB = new SystemDB();
        initializeStartupFrame();
    }

    private void initializeStartupFrame() {
        SwingUtilities.invokeLater(() -> {
            startupFrame = new JFrame("数据库初始化中...");
            startupFrame.setSize(300, 150);
            startupFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            startupFrame.setLocationRelativeTo(null);

            JLabel label = new JLabel("正在初始化数据库，请稍候...", SwingConstants.CENTER);
            startupFrame.add(label);

            startupFrame.setVisible(true);
        });
    }

    private void closeStartupFrame() {
        if (startupFrame != null) {
            startupFrame.dispose();
        }
    }

    public void initialize() {
        try (
                Connection connection = DriverManager.getConnection(SystemDB.URL, SystemDB.USER, SystemDB.PASSWORD);
                Statement statement = connection.createStatement()
        ) {
            // 创建数据库
            String createDatabase = "CREATE DATABASE IF NOT EXISTS " + SystemDB.NAME + ";";
            statement.executeUpdate(createDatabase);

            // 使用新创建的数据库
            statement.executeUpdate("USE " + SystemDB.NAME);

            // 创建用户表
            String createUserTable = "CREATE TABLE IF NOT EXISTS users (" 
                    + "id INT AUTO_INCREMENT PRIMARY KEY," 
                    + "phone VARCHAR(20) UNIQUE NOT NULL," 
                    + "username VARCHAR(50) NOT NULL," 
                    + "password VARCHAR(255) NOT NULL," 
                    + "register_time DATETIME NOT NULL," 
                    + "last_login_time DATETIME," 
                    + "avatar_url VARCHAR(255)" 
                    + ");"; 
            statement.executeUpdate(createUserTable);

            // 创建管理员表
            String createAdminTable = "CREATE TABLE IF NOT EXISTS administrators (" 
                    + "id INT AUTO_INCREMENT PRIMARY KEY," 
                    + "username VARCHAR(50) UNIQUE NOT NULL," 
                    + "password VARCHAR(255) NOT NULL" 
                    + ");"; 
            statement.executeUpdate(createAdminTable);

            closeStartupFrame();
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "数据库初始化失败，请检查数据库配置。", "错误", JOptionPane.ERROR_MESSAGE);
            closeStartupFrame();
            System.exit(1);
        }
    }

    public static void main(String[] args) {
        new DatabaseInitializer().initialize();
    }
}